<?php
namespace app\admin\controller;
use think\Db;
use think\Validate;
use think\Request;
use util\Tree;
use app\admin\model\Region as RegionModel;
/**
 * 地区管理控制器
 * @package app\admin\controller
 */
class Region extends Base
{
    /**
     * 首页
     * @author @author 唐小虎 <1731050423@qq.com>
     * @return mailparse_determine_best_xfer_encoding(fp)
     */
    public function index()
    {

        // 数据列表
        $data_list = RegionModel::order('id desc')->paginate();
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $this->assign('meta_title', '地区管理');
        $this->assign('list', $data_list);
        return $this->fetch();
    }

    /**
     * 新增
     * @author 唐小虎 <1731050423@qq.com>
     * @return mixed|void
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Region');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);
            // 添加数据
            if ($region = RegionModel::create($data)) {
                // 记录行为
                action_log('region_update', 'region', $region['id'], UID);
                return $this->success('新增成功', cookie('__forward__'));
            } else {
                return $this->error('新增失败');
            }
        }
        $this->assign('cate',RegionModel::getTree(null, '选择父级'));
        $this->assign('meta_title', '新增地区');
        return $this->fetch();
    }

    public function edit($id = '0')
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Region');
            // 验证失败 输出错误信息
            if (true !== $result) {
                return $this->error($result);
            }

            if ($region = RegionModel::update($data)) {               
                // Cache::clear();
                // 记录行为
                action_log('region_update', 'region', $region['id'], UID);
                $this->success('操作成功', cookie('__forward__'));
            } else {
                $this->error('操作失败', cookie('__forward__'));
            }
        }
        $this->assign('meta_title', '编辑文章');
        $this->assign('cate',RegionModel::getTree(null, '选择父级'));
        $info = RegionModel::get($id);
        $this->assign('info', $info);

        return $this->fetch();
    }
}
